#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"
#include "fcntl.h"

int mutex1;
int counter;
int num_of_threads;
int atz = 5;

void * atzeret(){
	int i, ans =1;
	for ( i =2; i <= atz;i++){
		ans = ans *i;
	}
	thread_exit(&ans);
	return 0;
}

void * print1 (){
	int i;
	thread_create(atzeret,malloc(4096),4096);
	for(i = 0; i < 100; i++){
		if(counter == 100)
			exit();
		binary_sem_down(mutex1);
		printf(1,"thread from proc %d with id %d\n",thread_getProcId(),thread_getid());
		printf(1,"thread from proc %d with id %d\n",thread_getProcId(),thread_getid());
		printf(1,"thread from proc %d with id %d\n",thread_getProcId(),thread_getid());
		printf(1,"\n");
		binary_sem_up(mutex1);
		counter++;
		printf(1, "counter is %d\n", counter);
	}
//	thread_exit(0);
	exit();
	return 0;
}

int
main(int argc, char *argv[]){
	
	counter = 0;
	num_of_threads = 0;
	mutex1 = binary_sem_create();
	binary_sem_down(mutex1);
	printf(1,"proc number %d has started\n",thread_getProcId());
	binary_sem_up(mutex1);
	if (fork() ==0){
		printf(1,"I'm the son. pid is %d\n", thread_getProcId());
		thread_exit(0);
	}
	else{
		int threads[3];
		int i;
		for(i = 0; i < 3; i++){
			threads[i] = thread_create(print1,malloc(4096),4096);
		}
		//wait();
		for(i = 0; i < 3; i++){
			thread_join(threads[i],0);
		}

		
		thread_exit(0);
	}
	return 1;
} 
